package org.iteam.xlz.manager.action.report;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.iteam.core.utils.DateUtil;
import org.iteam.web.struts.action.JsonServletAction;
import org.iteam.xlz.core.entity.product.ProductSale;
import org.iteam.xlz.core.entity.report.SaleReport;
import org.iteam.xlz.core.service.product.ProductSaleService;
import org.iteam.xlz.core.service.report.SaleReportService;

@Results({@Result(name="INDEX",type="freemarker",location="/WEB-INF/content/report/sale/index.html"),
	      @Result(name="DOWNLOAD",type="stream",params={"contentType","application/octet-stream",
	    		  "inputName","inputStream","contentDisposition","attachment;filename=${fileName}",
	    		  "bufferSize","4096"})})
public class SaleReportAction extends JsonServletAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = -6278721070618844730L;

	private final String PATH="/report/sale";
	
	@Action(PATH+"/index")
	public String index(){
		//map.put("products",ProductSaleService.getInstance().getOnSaleProduct());
		return "INDEX";
	}
	
	@Action(PATH+"/download")
	public String download() throws ParseException{
		setInputStream();
		return "DOWNLOAD";
	}
	
	public InputStream getInputStream() {
		return new ByteArrayInputStream(bytes);
	}
	
	private void setInputStream() throws ParseException{
		Date first = null;
		Date last = null;
		if(StringUtils.isNotBlank(leftCreateTime)||StringUtils.isNotBlank(rightCreateTime)){
			first=DateUtil.parseDate(leftCreateTime);
			last=DateUtil.parseDate(rightCreateTime);
		}
		List<ProductSale> list=ProductSaleService.getInstance().getOnSaleProduct(leftCreateTime,rightCreateTime);
		Map<String,List<SaleReport>> map=SaleReportService.getInstance().query(list,first,last);
		// 第一步，创建一个webbook，对应一个Excel文件
		HSSFWorkbook wb = new HSSFWorkbook();
		// 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
		HSSFSheet sheet = wb.createSheet("app统计表");
		// 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
		HSSFRow row = sheet.createRow(0);
		HSSFRow row1 = sheet.createRow(1);
		// 第四步，创建单元格
		//订单编号oid,手机号码uid,商品库存名称,商品上架名称ppid,票券编号tid,充值编号rid,交易号tradeNo,交易类型ordertype,总金额totalprice,数量amount,支付方式paytype,订单状态status,支付时间paytime,第三方流水号thirdid,创建时间createtime
		HSSFCell cell = row.createCell(0);
		cell.setCellValue("日期");
		CellRangeAddress region=new CellRangeAddress(0,1,0,0);
		sheet.addMergedRegion(region);
		int i=0;
		for(ProductSale sale:list){
			cell = row.createCell(1+3*i);
			cell.setCellValue(sale.getProductname());
			region=new CellRangeAddress(0,0,1+3*i,3+3*i);
			sheet.addMergedRegion(region);
			cell=row1.createCell(1+3*i);
			cell.setCellValue("待支付");
			cell=row1.createCell(2+3*i);
			cell.setCellValue("已完成");
			cell=row1.createCell(3+3*i);
			cell.setCellValue("退款/货");
			i++;
		}
		// 第五步，写入实体数据 实际应用中这些数据从数据库得到，
		Set<String> sets=map.keySet();
		i=2;
		for(String s:sets){
			List<SaleReport> sales=map.get(s);
			row=sheet.createRow(i);
			row.createCell(0).setCellValue(s);
			
			int j=1;
			for(SaleReport sr:sales){
				row.createCell(j++).setCellValue(sr.getOnSale());
				row.createCell(j++).setCellValue(sr.getComplete());
				row.createCell(j++).setCellValue(sr.getRefund());
			}
			i++;
		}
		// 第六步，将文件存到指定位置
		try
		{
			ByteArrayOutputStream  os=new ByteArrayOutputStream();
			wb.write(os);
			bytes=os.toByteArray();
			fileName = DateUtil.formatDate(new Date()) + new Random().nextInt(999)+".xls";//这里是给excel文件设置文件名（时间+一个随机数）
			wb.close();
		}catch (Exception e){
			e.printStackTrace();
		}
	}
	
	
	private String leftCreateTime;
	private String rightCreateTime;
	private byte[] bytes;
	private String fileName;
	
	int page,rows;
	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public int getRows() {
		return rows;
	}

	public void setRows(int rows) {
		this.rows = rows;
	}

	public void setLeftCreateTime(String leftCreateTime) {
		this.leftCreateTime = leftCreateTime;
	}

	public void setRightCreateTime(String rightCreateTime) {
		this.rightCreateTime = rightCreateTime;
	}

	public String getFileName() {
		return fileName;
	}
}
